package com.pactera.bledemo.activity.traditional

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.dylanc.viewbinding.nonreflection.binding
import com.pactera.bledemo.R
import com.pactera.bledemo.adapter.BleAdapter
import com.pactera.bledemo.base.BaseActivity
import com.pactera.bledemo.bean.BleBean
import com.pactera.library.bluetooth.Ble
import com.pactera.bledemo.databinding.ActivityClientBinding
import com.pactera.library.bluetooth.event.BleEvent
import com.pactera.library.listener.ConnectCallback
import com.pactera.library.listener.OnDataReceiveListener
import com.pactera.library.utils.ClsUtils
import com.pactera.library.utils.ToastUtil
import java.lang.Exception
import java.util.*

class ClientActivity : BaseActivity() {
    private val binding by binding(ActivityClientBinding::inflate)

    lateinit var mAdapter: BleAdapter


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ble = Ble.getInstance(this)
        binding.apply {
            mAdapter = BleAdapter();
            mRecyclerView.layoutManager = LinearLayoutManager(this@ClientActivity)
            mRecyclerView.adapter = mAdapter
            mAdapter.addChildClickViewIds(R.id.btnPair, R.id.tvConnect)
        }
        registerBleReceiver()

        if (!ble.isEnableBLE()) {
            //若没打开则打开蓝牙
            ble.enableBLE(this)
        } else {
            ble.startDiscoveryBLE();
        }
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            val item = mAdapter.getItem(position)
            val address = item.address
            val device1 = item.device

            goalAddressDevice = address

            when (view.id) {
                R.id.btnPair -> {
                    val result = ble.createBond(device1)
                    println("ClientActivity.onCreate result=$result")
                    if (result) {
                        ToastUtil.showToast("发起配对成功")
                    } else {
                        ToastUtil.showToast("发起配对失败")
                    }
                }
                R.id.tvConnect -> {
                    ble.connect(goalAddressDevice, object : ConnectCallback {
                        override fun connectCallback(bleEvent: BleEvent) {
                            if (bleEvent.connectResult) {
                                ToastUtil.showToast(bleEvent.connectMsg)
                                startActivity(Intent(mActivity, ClientDetailActivity::class.java))
                            } else {
                                ToastUtil.showToast("连接失败")
                            }
                        }

                    })
                }
                else -> {
                }
            }
        }


        ble.setOnDataReceiveListener(object : OnDataReceiveListener {
            override fun onDataReceive(result: String?) {

            }
        })


    }

    private fun registerBleReceiver() {
        val filter = IntentFilter()
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED)
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        filter.addAction(BluetoothDevice.ACTION_FOUND)

        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
        filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST)
        registerReceiver(receiver, filter)
    }

    private var goalAddressDevice: String? = null

    /**
     * 定义广播接收器
     */
    private val receiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            Log.i(TAG, "onReceive: action=$action")
            if (action == BluetoothAdapter.ACTION_DISCOVERY_STARTED) {
                Log.i(TAG, "onReceive:  扫描开始")
            } else if (action == BluetoothAdapter.ACTION_DISCOVERY_FINISHED) {
                Log.i(TAG, "onReceive:  扫描完成")
            } else if (action == BluetoothAdapter.ACTION_STATE_CHANGED) {
                Log.i(TAG, "onReceive: 状态改变广播")
            } else if (action == BluetoothDevice.ACTION_FOUND) {
                Log.i(TAG, "onReceive:  发现周围设备广播")
                val bluetoothDevice =
                    intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                val name = bluetoothDevice?.name
                val address = bluetoothDevice?.address
                Log.i(TAG, "onReceive:  name=$name address=$address")
                val mBean = BleBean();
                mBean.device = bluetoothDevice;
                mBean.name = name;
                mBean.address = address;
                mAdapter.addData(mBean)
            } else if (action == BluetoothDevice.ACTION_PAIRING_REQUEST) {
                Log.i(TAG, "onReceive: 配对请求广播")
                val btDevice =
                    intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                Log.i(
                    TAG,
                    "onReceive: btDevice.getAddress()=" + btDevice!!.address + "  goalAddressDevice=$goalAddressDevice"
                )
                if (btDevice.address == goalAddressDevice) {
                    val pin = "1234" //默认不是1234 就是 0000
                    try {
                        ClsUtils.setPairingConfirmation(btDevice.javaClass, btDevice, true) //1确认配对
                        abortBroadcast() //2.终止有序广播; 如果没有将广播终止，则会出现一个一闪而过的配对框。
                        val ret: Boolean =
                            ClsUtils.setPin(btDevice.javaClass, btDevice, pin) //3.调用setPin方法进行配对...
                        Log.i(TAG, "onReceive: ret=$ret")
                        if (ret) {
                            Toast.makeText(context, "配对成功", Toast.LENGTH_SHORT).show();
                            //把设备地址和名字保存到本地
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.i(TAG, "onActivityResult: 请求码=$requestCode 结果码=$resultCode")
        when (resultCode) {
            RESULT_OK -> {
                Log.i(TAG, "onActivityResult: 蓝牙已打开")
                ble.startDiscoveryBLE()
            }
            RESULT_CANCELED -> {
                Log.i(TAG, "onActivityResult: 打开请求被拒绝")
            }
            else -> {
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ble.cancelDiscoveryBLE()
        if (receiver != null) {
            unregisterReceiver(receiver)
        }
    }
}